package com.up.remoting.service;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;

import com.up.remoting.service.RemotingService;
import com.up.remoting.service.impl.AbstractRemotingService;

/**
 * 描述：将Cookie存储到文件cookie.txt中的服务实现。
 * 
 * @author xueqiang.mi
 * 
 */
public class MockRemotingService extends AbstractRemotingService implements RemotingService {
  private static final String COOKIE_FILE = "cookie.txt";
  private static final ClassLoader classLoader = MockRemotingService.class.getClassLoader();

  private static AbstractRemotingService instance;

  public static AbstractRemotingService getInstance() {
    if (instance == null) {
      instance = new MockRemotingService();
    }

    return instance;
  }

  @Override
  protected String getSessionId() {
    BufferedReader reader = null;
    try {
      String file = classLoader.getResource(COOKIE_FILE).getFile();
      reader = new BufferedReader(new FileReader(file));
      String line = reader.readLine();
      return line;
    } catch (Exception e) {
      // Ignore it.
    } finally {
      try {
        reader.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return null;
  }

  @Override
  protected void storeSessionId(String sessionId) {
    Writer writer = null;
    try {
      String file = classLoader.getResource(COOKIE_FILE).getFile();
      writer = new BufferedWriter(new FileWriter(file));
      writer.write(sessionId);
    } catch (Exception e) {
      // Ignore it.
    } finally {
      try {
        writer.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

}
